﻿using Microsoft.AspNetCore.Mvc;
using Water_and_electricity_metering_management_system.Models.Dtos;
using Water_and_electricity_metering_management_system.Models.Entitys;
using Water_and_electricity_metering_management_system.Models.Utils;

namespace Water_and_electricity_metering_management_system.Controllers
{
    public class UserController : Controller
    {
        WemmsDbContext dbContext = new WemmsDbContext();

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        public IActionResult LoginView()
        {
            HashSet<string> BuidingNames = new HashSet<string>();
            foreach (Buiding buiding in dbContext.Buidings)
            {
                BuidingNames.Add(buiding.BuidingName);
            }

            ViewBag.Buildings = BuidingNames.ToList();

            return View();
        }
        /// <summary>
        /// 登录操作
        /// </summary>
        [HttpPost]
        public HttpResult BuidingLogin(BuidingLogin buidingLogin)
        {
            if (buidingLogin == null)
            {
                return HttpResult.Failure("前端传递参数错误", null);
            }
            if (buidingLogin.HomeNumbe == null)
            {
                return HttpResult.Failure("输入房间号不存在", null);
            }

            // 找到楼栋和房间号相同的记录
            Buiding LoginBuiding = dbContext.Buidings.Select(b => b).Where(b => b.BuidingName == buidingLogin.BuildingName.Trim() && b.HomeNumbe == buidingLogin.HomeNumbe).FirstOrDefault();

            if(LoginBuiding == null)
            {
                return HttpResult.Failure("系统错误", null);
            }

            // 将登录信息存入Session
            HttpContext.Session.SetString("BuidingName", LoginBuiding.BuidingName.Trim());
            HttpContext.Session.SetInt32("HomeNumbe", LoginBuiding.HomeNumbe);

            // Response.Redirect("/Home/Index");

            return HttpResult.Success("/Home/Index");
        }


    }
}
